﻿using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Config;
using SuperSocket.WebSocket;

namespace MyServer.Code
{
    /// <summary>
    /// 网络管理器
    /// </summary>
    public class MySocketManager :Singleton<MySocketManager>
    {
        /// <summary>
        /// 服务器
        /// </summary>
        public WebSocketServer Socket { get { return socket; } }
        private WebSocketServer socket = null;

        /// <summary>
        /// 服务器是否运行中
        /// </summary>
        public bool IsRunning { get { return socket != null && socket.State == ServerState.Running; } }

        /// <summary> 
        /// 启动服务器
        /// </summary>
        /// <param name="port">端口号</param>
        public void ServerStart(int port)
        {
            ServerClose();
             
            socket = new WebSocketServer();

            if (!socket.Setup(GetServerConfig(port)))
            {
                Tool.Log("服务器设置失败！");
                return;
            }
            if (!socket.Start())
            {
                Tool.Log("服务器启动失败！");
                return;
            }

            socket.NewSessionConnected += NewSessionConnected;
            socket.SessionClosed += SessionClosed;
            socket.NewDataReceived += NewDataReceived;

            MessageHandler.Instance.Open();
            Tool.Log("服务器启动成功！", true);
        }

        /// <summary>
        /// 关闭服务器
        /// </summary>
        public void ServerClose()
        {
            if (socket == null)
                return;
            MessageHandler.Instance.Close();

            socket.NewSessionConnected -= NewSessionConnected;
            socket.SessionClosed -= SessionClosed;
            socket.NewDataReceived -= NewDataReceived;

            socket.Stop();
            socket = null;

            Tool.Log("服务器已经关闭！", true);
        }

        /// <summary>
        /// 获得服务器配置
        /// </summary>
        /// <param name="port">端口</param>
        /// <returns>服务器配置</returns>
        private ServerConfig GetServerConfig(int port)
        {
            ServerConfig config = new ServerConfig();
            //端口
            config.Port = port;
            //最大连接数
            config.MaxConnectionNumber = 10000;
            //最大包长度
            config.MaxRequestLength = 1024;
            //60秒清理一次90秒没数据传送的连接
            config.ClearIdleSession = true;
            config.ClearIdleSessionInterval = 60;
            config.IdleSessionTimeOut = 90;
            return config;
        }

        /// <summary>
        /// 客户端连接
        /// </summary>
        /// <param name="session">客户端</param>
        private void NewSessionConnected(WebSocketSession session)
        {
            session.Send(MsgType.回调, "NewSessionConnected");
        }

        /// <summary>
        /// 客户端关闭
        /// </summary>
        /// <param name="session">客户端</param>
        /// <param name="value">关闭原因</param>
        private void SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
        {
            Tool.Log(session.Host.Format() + "SessionClosed：" + value.ToString());
        }

        /// <summary>
        /// 接到字节消息
        /// </summary>
        /// <param name="session">客户端</param>
        /// <param name="value">字节</param>
        private void NewDataReceived(WebSocketSession session, byte[] value)
        {
            byte[] data = null;
            MsgType type = value.ParseMessageType(out data);
            MessageHandler.Instance.HandleMessage(session, type, data);
        }
    }
}
